//
//  NSString+Category.m
//  lc-collect
//
//  Created by mac on 2021/3/2.
//

#import "NSString+Category.h"

static NSCharacterSet *VariationSelectors = nil;

@implementation NSString (Category)

#pragma mark - 转化

/// 字典转Json字符串
+ (NSString *)dicToJSONStringWith:(NSDictionary *)dic {
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
       return nil;
    }else{
       jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    //去掉字符串中的空格
    NSRange range = {0,jsonString.length};
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    //去掉字符串中的换行符
    NSRange range2 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
}

/// JSON字符传转化成字典
- (NSDictionary *)jsonStringToDictionary {
    
    if (self == nil) {
        return nil;
    }
    NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
           return nil;
    }
    
    return dic;
}

/// NSString转为NSNumber
- (NSNumber *)stringToNumber {
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *number=[formatter numberFromString:self];
    
    return number;
}

#pragma mark - other

/// 取出HTML
- (NSString *)htmlToString {
    
    if (self == nil) {
        return nil;
    }
    NSString *html = self;
    NSScanner *scanner = [NSScanner scannerWithString:html];
    NSString *text = nil;
    
    while([scanner isAtEnd] == NO) {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    
    return html;
}

/// 抹除小数末尾的0
- (NSString *)removeUnwantedZero {
    
    if ([[self substringWithRange:NSMakeRange(self.length- 3, 3)] isEqualToString:@"000"]) {
        return [self substringWithRange:NSMakeRange(0, self.length-4)]; // 多一个小数点
    } else if ([[self substringWithRange:NSMakeRange(self.length- 2, 2)] isEqualToString:@"00"]) {
        return [self substringWithRange:NSMakeRange(0, self.length-2)];
    } else if ([[self substringWithRange:NSMakeRange(self.length- 1, 1)] isEqualToString:@"0"]) {
        return [self substringWithRange:NSMakeRange(0, self.length-1)];
    } else {
        return self;
    }
}

/// 去掉前后空格
- (NSString *)trimmedString {
    
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
}

/// 电话号码中间4位*显示 135*****262
/// @param phoneNum 电话号码
+ (NSString *)getSecrectStringWithPhoneNumber:(NSString*)phoneNum {
    
    if (phoneNum.length == 11) {
        NSMutableString *newStr = [NSMutableString stringWithString:phoneNum];
        NSRange range = NSMakeRange(3, 7);
        [newStr replaceCharactersInRange:range withString:@"*****"];
        return newStr;
    }
    
    return nil;
}

/// 银行卡号中间8位*显示
/// @param accountNo 银行卡号
+ (NSString *)getSecrectStringWithAccountNo:(NSString*)accountNo {
    
    NSMutableString *newStr = [NSMutableString stringWithString:accountNo];
    NSRange range = NSMakeRange(4, 8);
    if (newStr.length > 12) {
        [newStr replaceCharactersInRange:range withString:@" **** **** "];
    }
    
    return newStr;
}

/// 转为手机格式，默认为-
/// @param mobile mobile
+ (NSString *)stringMobileFormat:(NSString*)mobile {
    
    if (mobile.length == 11) {
        NSMutableString* value = [[NSMutableString alloc] initWithString:mobile];
        [value insertString:@"-" atIndex:3];
        [value insertString:@"-" atIndex:8];
        return value;
    }
    
    return nil;
}

/// 金额数字添加单位（暂时写了万和亿，有更多的需求请参考写法来自行添加）
/// @param value 金额
+ (NSString *)stringChineseFormat:(double)value {
    
    if (value / 100000000 >= 1) {
        return [NSString stringWithFormat:@"%.0f亿", value/100000000];
    }
    else if (value / 10000 >= 1 && value / 100000000 < 1) {
        return [NSString stringWithFormat:@"%.0f万", value/10000];
    }
    else {
        return [NSString stringWithFormat:@"%.0f", value];
    }
}

/// 添加数字的千位符
/// @param num #
+ (NSString *)countNumAndChangeformat:(NSString *)num {
    
    NSNumberFormatter *moneyFormatter = [[NSNumberFormatter alloc] init];
    moneyFormatter.positiveFormat = @"###,###";
    
    //如要增加小数点请自行修改为@"###,###,##"
    return [moneyFormatter stringFromNumber:[num stringToNumber]];
}

/// 生成随机字符串
+ (NSString *)getRandomString:(NSInteger)place {
    
    NSString *string = [[NSString alloc] init];
    for (int i = 0; i < place; i++) {
        int number = arc4random() % 36;
        if (number < 10) {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
        } else {
            int figure = (arc4random() % 26) + 97;
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            string = [string stringByAppendingString:tempString];
        }
    }
    
    return string;
}

/// 复制到粘贴板
- (void)copyToPasteboard {
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self;
}

/// 打电话
- (void)makePhone {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *phone = [NSString stringWithFormat:@"telprompt://%@", self];
        NSURL *phoneURL = [NSURL URLWithString:phone];
//        [[UIApplication sharedApplication] openURL:phoneURL];
        [[UIApplication sharedApplication] openURL:phoneURL options:@{} completionHandler:nil];
    });
}

#pragma mark - base64

/// 字符串加密为base64
- (NSString *)base64StringFromText {
    
    NSData *nsdata = [self dataUsingEncoding:NSUTF8StringEncoding];
    
    // Get NSString from NSData object in Base64
    NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];
    
    // Print the Base64 encoded string
    return  base64Encoded;
}

/// 加密字符串解析
- (NSString *)textFromBase64String {
    
    NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:self options:0];
    
    // Decoded NSString from the NSData
    NSString *base64Decoded = [[NSString alloc] initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
    
    return base64Decoded;
}

#pragma mark - URL
/// URL编码
- (NSString *)lc_UrlEncodedString {
    
    return [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"!*'\"();:@&=+$,/?%#[]% "].invertedSet];
}

/// URL解码
- (NSString *)lc_UrlDecodedString {
    
    return [self stringByRemovingPercentEncoding];
}

#pragma mark - 计算size

/// 计算文字高度
/// @param fontSize 字体
/// @param width 最大宽度
- (CGFloat)heightWithFontSize:(CGFloat)fontSize width:(CGFloat)width {
    
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    CGFloat height = [self boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.height;
    
    return height;
}

/// 计算文字宽度
/// @param fontSize 字体
/// @param maxHeight 最大高度
- (CGFloat)widthWithFontSize:(CGFloat)fontSize height:(CGFloat)maxHeight {
    
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    CGFloat width = [self boundingRectWithSize:CGSizeMake(0, maxHeight) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.width;
    
    return width;
}

#pragma mark - 判断

/// 密码是否为数字和字母混合 strong password
- (BOOL)isPasswordStrong {
    
    // 不允许含 emoji
    if ([self isContainsEmoji]) {
        return false;
    }
    
    // digital
    NSRange digitalRange = [self rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
    // letter
    NSRange letterRange = [self rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
    
    if (digitalRange.location != NSNotFound && letterRange.location != NSNotFound) {
        return true;
    }
    
    return false;
}

/// 是否在范围内
/// @param min 小
/// @param max 大
- (BOOL)isLengthInRange:(NSInteger)min max:(NSInteger)max {
    
    return self.length >= min && self.length <= max;
}

/// emoji 检查
- (BOOL)isContainsEmoji {
    
    __block BOOL containsEmoji = NO;
    
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        
        const unichar hs = [substring characterAtIndex:0];
        
        // surrogate pair
        if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f9c0) {
                     containsEmoji = YES;
                 }
             }
         }
         else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3 || ls == 0xfe0f || ls == 0xd83c) {
                 containsEmoji = YES;
             }
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 containsEmoji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 containsEmoji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 containsEmoji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 containsEmoji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 containsEmoji = YES;
             }
         }
     }];
    
    return containsEmoji;
}

///判断当前字符是否emoji
- (BOOL)isEmoji {
    
    if ([self rangeOfCharacterFromSet:VariationSelectors].location != NSNotFound) {
        return YES;
    }
    
    const unichar high = [self characterAtIndex: 0];
    
    // Surrogate pair (U+1D000-1F9FF)
    if (0xD800 <= high && high <= 0xDBFF) {
        const unichar low = [self characterAtIndex: 1];
        const int codepoint = ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
        
        return (0x1D000 <= codepoint && codepoint <= 0x1F9FF);
        
        // Not surrogate pair (U+2100-27BF)
    } else {
        return (0x2100 <= high && high <= 0x27BF);
    }
}

/// 空
+ (BOOL)isEmpty:(NSString *)str {
    return [str isEmpty];
}

- (BOOL)isEmpty {
    
    if (self == nil || self == NULL || [self isKindOfClass:[NSNull class]] || [self length] == 0 || [self isEqualToString: @"(null)"]) {
        return YES;
    }
    
    return NO;
}


@end
